package com.rykj.qxj.server.common.utils.generator;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.lang.reflect.Field;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.apache.commons.lang.StringUtils;



/**
 * 此类的代码应该进行重点梳理。
 * @author wangshunyi
 *
 */
public class BaseGeneratorUtils {
	
	private final static String CAMEL_PATTERN = "[A-Z]([a-z\\d]+)?";
	private final static String ANNOTATION_PATTERN = "/\\*\\*.*\\*/";
	private final static String ENUM_PATTERN = "\".*\"";
	
	/**
	 * 驼峰法转下划线
	 * 
	 * @param line
	 *            源字符串
	 * @return 转换后的字符串
	 */
	protected static String camel2Underline(String line) {
		if (line == null || "".equals(line)) {
			return "";
		}
		line = String.valueOf(line.charAt(0)).toUpperCase().concat(line.substring(1));
		StringBuffer sb = new StringBuffer();
		Pattern pattern = Pattern.compile(CAMEL_PATTERN);
		Matcher matcher = pattern.matcher(line);
		while (matcher.find()) {
			String word = matcher.group();
			sb.append(word.toUpperCase());
			sb.append(matcher.end() == line.length() ? "" : "_");
		}
		return sb.toString().toLowerCase();
	}

	/**
	 * 读取java源文件
	 */
	protected static String readJavaFile(Class clazz) {
		String path = clazz.getResource("").toString().replace("/target/classes", "/src/main/java")
				+ clazz.getSimpleName() + ".java";
		StringBuilder sb = new StringBuilder();
		path = path.replace("file:/", "");
		File file = new File(path);
		if (file.isFile() && file.exists()) {
			InputStreamReader read = null;
			try {
				read = new InputStreamReader(new FileInputStream(file), "UTF-8");
				BufferedReader bufferedReader = new BufferedReader(read);
				String lineTxt = null;
				while ((lineTxt = bufferedReader.readLine()) != null) {
					sb.append(lineTxt).append("\n");
				}
			} catch (IOException e) {
				e.printStackTrace();
			} finally {
				try {
					read.close();
				} catch (IOException e) {
				}
			}
		}
		return sb.toString();
	}

	/**
	 * 获取注释
	 * 
	 * @param java
	 *            源代码
	 * @param filed
	 *            字段名
	 * @return
	 */
	protected static String getJavaAnnotation(String java, String filed) {
		String[] lines = java.split("\n");
		int i = 0;
		for (String line : lines) {
			if (line.indexOf(filed + ";") != -1 || Pattern.matches(".*" + filed + "\\s*" + "\\{", line)) {
				break;
			}
			i++;
		}
		int end = --i;
		int start = 0;
		for (; i >= 0; i--) {
			if (lines[i].indexOf(";") != -1 || lines[i].indexOf("{") != -1) {
				start = i;
				break;
			}
		}
		StringBuilder annotation = new StringBuilder();
		int cursor = start;
		// /***/注释
		StringBuilder sb = new StringBuilder();
		for (cursor++; cursor <= end; cursor++) {
			sb.append(lines[cursor]);
		}
		Pattern p = Pattern.compile(ANNOTATION_PATTERN);
		Matcher m = p.matcher(sb.toString());
		sb = new StringBuilder();
		while (m.find()) {
			sb.append(m.group());
		}
		String a = sb.toString().replace("/**", "").replace("*/", "");
		a = a.replaceAll("(\\t|\\*| )*", "");
		annotation.append(a).append(" ");
		// //注释
		cursor = start;
		for (cursor++; cursor <= end; cursor++) {
			String line = lines[cursor];
			if (line.indexOf("//") != -1) {
				annotation.append(StringUtils.trim(line).replace("//", ""));
			}
		}
		String result = annotation.toString().trim();
		if(StringUtils.isEmpty(result) && "id".equals(filed)){
			result = "编号";
		}
		return result;
	}

	/**
	 * 获取 enum value值
	 */
	protected static String getEnumValue(String java, String filed) {
		String[] lines = java.split("\n");
		int i = 0;
		for (String line : lines) {
			if (line.indexOf(filed) != -1) {
				Pattern p = Pattern.compile(ENUM_PATTERN);
				Matcher m = p.matcher(lines[i]);
				if (m.find()) {
					return m.group().replaceAll("\"", "");
				}
			}
			i++;
		}
		return filed;
	}
	/**
	 * 获取列名 考虑驼峰及外键
	 */
	protected static String getColumn(Field field) {
		if (isModel(field)) {
			return BaseGeneratorUtils.camel2Underline(field.getName()) + "_id";
		} else {
			return BaseGeneratorUtils.camel2Underline(field.getName());
		}
	}

	/**
	 * 获取属性名 考虑外键
	 */
	protected static String getFieldName(Field field) {
		if (isModel(field)) {
			return field.getName() + ".id";
		} else {
			return field.getName();
		}
	}
	
	/**
	 * 是否是外键
	 */
	protected static boolean isModel(Field field){
		return field.getGenericType().getTypeName().indexOf(".model.") != -1;
	}
	
	/**
	 * 是否是玫举
	 * field.isEnumConstant并不是很好用
	 */
	protected static boolean isEnum(Field field){
		return field.getGenericType().getTypeName().indexOf(".constants.") != -1;
	}

	/**
	 * 写入文件
	 * 
	 * @param path
	 *            文件路径
	 * @param source
	 *            写入内容
	 * @return 是否写入文件。文件已存在时不执行写入操作
	 */
	protected static boolean writeIntoFile(String path, String source) {
		boolean b = false;
		path = path.replace("file:/", "");
		File file = new File(path);
		String pathFolder = path.substring(0, path.lastIndexOf("/"));
		File folder = new File(pathFolder);
		FileOutputStream fos = null;
		try {
			if(!folder.exists()){
				folder.mkdirs();
			}
			if (!file.exists()) {
				file.createNewFile();
				fos = new FileOutputStream(file);
				fos.write(source.getBytes());
				b = true;
			}
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			if (fos != null) {
				try {
					fos.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
		return b;
	}
	
	/**
	 * 首字母小写
	 * @param name
	 * @return
	 */
	protected static String captureName(String name) {
		char[] cs = name.toCharArray();
		cs[0] += 32;
		return String.valueOf(cs);

	}
}
